package org.darkforest.admin.controller;


import org.apache.commons.lang3.StringUtils;
import org.darkforest.annotation.ArchivesLog;
import org.darkforest.common.services.GoodsClassRedisService;
import org.darkforest.common.services.GoodsService;
import org.darkforest.common.services.GoodsTagService;
import org.darkforest.common.services.IAlbumClassService;
import org.darkforest.common.util.DateUtil;
import org.darkforest.common.util.Page;
import org.darkforest.common.util.TreeListUtil;
import org.darkforest.common.util.Utils;
import org.darkforest.controller.WebController;
import org.darkforest.dao.mapper.*;
import org.darkforest.enums.AjaxMsgTypeEnum;
import org.darkforest.model.*;
import org.darkforest.ucenter.auth.AuthPassport;
import org.darkforest.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by valentina on 15/5/11.
 * 商品控制类
 */
@Controller
@RequestMapping("goods")
public class GoodsController extends WebController<GoodsController> {

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private GoodsClassMapper goodsClassMapper;

    @Autowired
    private GoodsCommonMapper goodsCommonMapper;

    @Autowired
    private GoodsCommonProxyMapper goodsCommonProxyMapper;

    @Autowired
    private SpecMapper specMapper;

    @Autowired
    private SpecValueMapper specValueMapper;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private AttributeMapper attributeMapper;

    @Autowired
    private AlbumClassMapper albumClassMapper;

    @Autowired
    private AlbumPicMapper picDao;

    @Autowired
    private GoodsClassRedisService goodsClassRedisService;


    @Autowired
    private GoodsTagService goodsTagService;

    @Autowired
    private FestivalMapper festivalMapper;

    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private ActiveAreaGoodsMapper activeAreaGoodsMapper;

    /**
     * 根据商品ID获取商品详情
     * @param goodsCommonid
     * @return
     */
    @RequestMapping(value = "getGoodsByGoodsCommonid")
    public @ResponseBody GoodsCommon getGoodsByGoodsCommonid(Integer goodsCommonid){
        return  goodsCommonMapper.selectByPrimaryKey(goodsCommonid);
    }

    /**
     * redis获取商品分类列表
     *
     * @param gcId
     * @return
     */
    @RequestMapping(value = "goodsClass/goodsClassByGcId")
    public
    @ResponseBody
    List<GoodsClass> goodsClassByGcId(@RequestParam(required = false, defaultValue = "") Integer gcId) {
        List<GoodsClass> goodsClassList = null;
        if ("".equals(gcId)) {
            goodsClassList = goodsClassRedisService.getGoodsClassList(null);

        } else {
            goodsClassList = goodsClassRedisService.getGoodsClassList(gcId);
        }

        return goodsClassList;
    }

    @Value("#{configProperties['pic.compressSize']}")
    private String compressPicSize;                     //图片压缩尺寸从配置文件中读取
    @Value("#{configProperties['pic.tempPath']}")
    private String picTempPath;                         //图片上传临时目录,避免写死尽量配置为变量


    /**
     * 品牌列表
     *
     * @return
     */
    @RequestMapping("brand")
    public ModelAndView list(Brand brand) {
        ModelAndView modelAndView = new ModelAndView("goods/brand_list");
        List<Brand> brandList = brandMapper.findBrandByCondition(brand);
        brand.setResultList(brandList);
        modelAndView.addObject("page", brand);
        return modelAndView;
    }

    /**
     * to-------增加品牌
     *
     * @return
     */
    @RequestMapping("brand/toAdd")
    public ModelAndView brandAdd() {
        ModelAndView modelAndView = new ModelAndView("goods/brand_add");
        GoodsClass goodsClass = new GoodsClass();
        goodsClass.setGcParentId(0);
        goodsClass.setPageSwitch(false);
        List<GoodsClass> goodsClassList = goodsClassMapper.findGoodsClass(goodsClass);
        modelAndView.addObject("goodsClassList", goodsClassList);
        return modelAndView;
    }

    /**
     * 品牌名称检查是否重复
     *
     * @param brandName
     * @return
     */
    @RequestMapping("brand/checkBrandName")
    public
    @ResponseBody
    boolean checkBrandName(String brandName) {
        Brand brand = new Brand();
        brand.setBrandName(brandName);
        List<Brand> brandList = this.brandMapper.findBrandByCondition(brand);
        if (brandList.size() > 0) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * do------新增品牌
     */
    @ArchivesLog(operationDescription = "新增商品品牌")
    @RequestMapping("brand/doAdd")
    public ModelAndView add(MultipartHttpServletRequest multipartHttpServletRequest) {

        ModelAndView modelAndView = new ModelAndView("msg");
        Brand brand = new Brand();
        brand.setBrandName(multipartHttpServletRequest.getParameter("brandName"));
        brand.setBrandClass(multipartHttpServletRequest.getParameter("brandClass"));
        brand.setBrandInitial(multipartHttpServletRequest.getParameter("brandInitial"));
//        brand.setBrandPic(multipartHttpServletRequest.getParameter("brandClass"));
        brand.setBrandRecommend(Byte.parseByte(multipartHttpServletRequest.getParameter("brandRecommend")));
        brand.setBrandSort(Integer.parseInt(multipartHttpServletRequest.getParameter("brandSort")));
        brand.setStoreId(1); //暂时先用固定1 登录功能完成后从session中取
        brand.setBrandApply((byte) 0);
        String classId = multipartHttpServletRequest.getParameter("classId");
        if(classId!=null&&!classId.equals("")){
            brand.setClassId(Integer.parseInt(multipartHttpServletRequest.getParameter("classId")));
        }
        brand.setWapIndex(multipartHttpServletRequest.getParameter("wapIndex"));
        MultipartFile BrandPicturempf = multipartHttpServletRequest.getFile("brandPicture");
        if(BrandPicturempf!=null&&BrandPicturempf.getSize()>0){
            String BrandPicture = super.uploadPicsWithoutCompressSize(BrandPicturempf, multipartHttpServletRequest, null, null);
            brand.setBrandPic(BrandPicture);
        }
        MultipartFile wapAdvPicmpf = multipartHttpServletRequest.getFile("wapAdvPic");
        if(wapAdvPicmpf!=null&&wapAdvPicmpf.getSize()>0){
            String wapAdvPic = super.uploadPicsWithoutCompressSize(wapAdvPicmpf, multipartHttpServletRequest, null, null);
            brand.setWapAdvPic(wapAdvPic);
        }
        brand.setWapAdvUrl(multipartHttpServletRequest.getParameter("wapAdvUrl"));
        int i = brandMapper.insert(brand);
        if (i > 0) {
            modelAndView.addObject("msg", "商品品牌新增成功");
        } else {
            modelAndView.addObject("msg", "商品品牌新增失败");
        }
        modelAndView.addObject("returnUrl", "goods/brand");
        return modelAndView;
    }


    @RequestMapping("brand/toModify")
    public ModelAndView toModifyBrand(Integer brandId) {
        ModelAndView modelAndView = new ModelAndView("goods/brand_modify");
        Brand brand = this.brandMapper.selectByPrimaryKey(brandId);
        GoodsClass goodsClass = new GoodsClass();
        goodsClass.setGcParentId(0);
        goodsClass.setPageSwitch(false);
        List<GoodsClass> goodsClassList = goodsClassMapper.findGoodsClass(goodsClass);
        modelAndView.addObject("goodsClassList", goodsClassList);
        modelAndView.addObject("brand", brand);
        return modelAndView;
    }
    @ArchivesLog(operationDescription = "设置推荐品牌")
    @RequestMapping("brand/editbrandRecommend")
    public ModelAndView editbrandRecommend(int id, Byte brandRecommend) {
        ModelAndView modelAndView = new ModelAndView("redirect:/goods/brand");
        Brand brand = brandMapper.selectByPrimaryKey(id);
        brand.setBrandRecommend(brandRecommend);
        brandMapper.updateByPrimaryKeySelective(brand);
        return modelAndView;
    }

    @ArchivesLog(operationDescription = "修改商品品牌")
    @RequestMapping("brand/doModify")
    public ModelAndView doModifyBrand(MultipartHttpServletRequest multipartHttpServletRequest) {
        ModelAndView modelAndView = new ModelAndView("msg");

        Brand brand = new Brand();
        brand.setBrandId(Integer.parseInt(multipartHttpServletRequest.getParameter("brandId")));
        brand.setBrandName(multipartHttpServletRequest.getParameter("brandName"));
        brand.setBrandClass(multipartHttpServletRequest.getParameter("brandClass"));
        brand.setBrandInitial(multipartHttpServletRequest.getParameter("brandInitial"));
        brand.setBrandRecommend(Byte.parseByte(multipartHttpServletRequest.getParameter("brandRecommend")));
        brand.setBrandSort(Integer.parseInt(multipartHttpServletRequest.getParameter("brandSort")));
        brand.setWapIndex(multipartHttpServletRequest.getParameter("wapIndex"));
        brand.setStoreId(1); //暂时先用固定1 登录功能完成后从session中取
        brand.setBrandApply((byte) 0);
        String classId = multipartHttpServletRequest.getParameter("classId");
        if(classId!=null&&!classId.equals("")){
            brand.setClassId(Integer.parseInt(multipartHttpServletRequest.getParameter("classId")));
        }
        MultipartFile BrandPicturempf = multipartHttpServletRequest.getFile("brandPicture");
        if (BrandPicturempf!=null&&BrandPicturempf.getSize() > 0) {
            String BrandPicture = super.uploadPicsWithoutCompressSize(BrandPicturempf, multipartHttpServletRequest, null, null);
            brand.setBrandPic(BrandPicture);
        }
        MultipartFile wapAdvPicmpf = multipartHttpServletRequest.getFile("wapAdvPic");
        if (wapAdvPicmpf!=null&&wapAdvPicmpf.getSize() > 0) {
            String wapAdvPic = super.uploadPicsWithoutCompressSize(wapAdvPicmpf, multipartHttpServletRequest, null, null);
            brand.setWapAdvPic(wapAdvPic);
        }
        brand.setWapAdvUrl(multipartHttpServletRequest.getParameter("wapAdvUrl"));
        int i = brandMapper.updateByPrimaryKeySelective(brand);
        if (i > 0) {
            modelAndView.addObject("msg", "商品品牌修改成功");
        } else {
            modelAndView.addObject("msg", "商品品牌修改失败");
        }
        modelAndView.addObject("returnUrl", "goods/brand");

        return modelAndView;
    }

    @ArchivesLog(operationDescription = "删除商品品牌")
    @RequestMapping("brand/delBrand")
    public ModelAndView delBrand(HttpServletRequest request) {
        String[] brandId = request.getParameterValues("brandIds");
        int i = 0;
        for (String id : brandId) {
            i += brandMapper.deleteByPrimaryKey(Integer.parseInt(id));

        }
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i == brandId.length) {
            modelAndView.addObject("msg", "商品品牌删除成功");
        } else {
            modelAndView.addObject("msg", "商品品牌删除失败");
        }
        modelAndView.addObject("returnUrl", "goods/brand");
        return modelAndView;
    }

    @RequestMapping("goodsList")
    public ModelAndView goodsList(GoodsCommonPage goodsCommonPage, HttpServletRequest request, String type) {
        // 改页处理用
        String start = request.getParameter("start");
        if (start != null && !"".equals(start)) {
            goodsCommonPage.setStart(Integer.valueOf(start));
        }
        ModelAndView modelAndView = new ModelAndView("goods/goods_list");
        List<GoodsCommonProxyVO> goodsCommonProxyVOList = this.goodsCommonMapper.findGoodsForProxy(goodsCommonPage);
        Brand band = new Brand();
        band.setPageSwitch(false);
        List<Brand> brandList = this.brandMapper.findBrandByCondition(band);
        goodsCommonPage.setResultList(goodsCommonProxyVOList);
        modelAndView.addObject("page", goodsCommonPage);
        modelAndView.addObject("brandList", brandList);
        modelAndView.addObject("type", type);
        return modelAndView;
    }

    @RequestMapping("goodsList/SearchGoodsCommonProxy")
    public ModelAndView SearchGoodsCommonProxy(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("goods/goods_list");
        GoodsCommonPage modelPage = new GoodsCommonPage();
        // 改页处理用
        String start = request.getParameter("start");
        if (start != null && !"".equals(start)) {
            modelPage.setStart(Integer.valueOf(start));
        }
        String goodsName = request.getParameter("goodsName");
        String storeName = request.getParameter("storeName");
        String brandId = request.getParameter("brandId");
        String brandName = request.getParameter("brandName");
        String goodsCommonid = request.getParameter("goodsCommonid");
        String goodsState = request.getParameter("goodsState");
        String goodsVerify = request.getParameter("goodsVerify");
        if (Utils.isNotEmpty(goodsName)) {
            modelPage.setGoodsName(goodsName);
            modelAndView.addObject("goodsName", goodsName);
        }
        if (Utils.isNotEmpty(storeName)) {
            modelPage.setStoreName(storeName);
            modelAndView.addObject("storeName", storeName);
        }
        if (Utils.isNotEmpty(brandId)) {
            modelPage.setBrandId(Integer.parseInt(brandId));
            modelAndView.addObject("brandId", brandId);
            modelAndView.addObject("brandName", brandName);
        }
        if (Utils.isNotEmpty(goodsCommonid)) {
            modelPage.setGoodsCommonId(Integer.valueOf(goodsCommonid));
            modelAndView.addObject("goodsCommonid", goodsCommonid);
        }
        if (Utils.isNotEmpty(goodsState)) {
            modelPage.setGoodsState(goodsState);
        }
        if (Utils.isNotEmpty(goodsVerify)) {
            modelPage.setGoodsVerify(goodsVerify);
        }

        List<GoodsCommonProxyVO> goodsCommonProxyVOList = this.goodsCommonMapper.findGoodsForProxy(modelPage);
        Brand brand = new Brand();
        brand.setPageSwitch(false);
        List<Brand> brandList = this.brandMapper.findBrandByCondition(brand);
        modelPage.setResultList(goodsCommonProxyVOList);

        modelAndView.addObject("page", modelPage);
        modelAndView.addObject("brandList", brandList);
        return modelAndView;
    }

    @RequestMapping("searchBrandAjax")
    public
    @ResponseBody
    List<Brand> searchBrandAjax(HttpServletRequest request) {
        Brand brand = new Brand();
        String type = request.getParameter("type");
        if ("1".equals(type)) { //关键字搜索
            brand.setBrandName(request.getParameter("keyword"));

        } else {
            brand.setBrandInitial(request.getParameter("keyword"));
        }
        List<Brand> brandList = this.brandMapper.findBrandByCondition(brand);
        return brandList;
    }

    @RequestMapping("toSetGoodsProxyPrice")
    public ModelAndView toSetGoodsProxyPrice(Integer goodsCommonId) {
        ModelAndView modelAndView = new ModelAndView("goods/goods_proxy_price");
        GoodsCommonPage modelPage = new GoodsCommonPage(1, Page.DEFAULT_PAGE_SIZE);
        modelPage.setGoodsCommonId(goodsCommonId);
        List<GoodsCommonProxyVO> goodsInfo = this.goodsCommonMapper.findGoodsForProxy(modelPage);
        modelAndView.addObject("goodsInfo", goodsInfo.size() > 0 ? goodsInfo.get(0) : null);
        return modelAndView;

    }

    @ArchivesLog(operationDescription = "设置商品代理价格")
    @RequestMapping("doSetGoodsProxyPrice")
    public ModelAndView doSetGoodsProxyPrice(HttpServletRequest request) {
        GoodsCommonProxy goodsCommonProxy = new GoodsCommonProxy();
        goodsCommonProxy.setGoodsCommonid(Integer.parseInt(request.getParameter("goodsCommonId")));
        goodsCommonProxy.setProxyPriceLv1(new BigDecimal(request.getParameter("proxyPriceLv1")));
        goodsCommonProxy.setProxyPriceLv2(new BigDecimal(request.getParameter("proxyPriceLv2")));

        goodsCommonProxy.setProxyPriceLv3(new BigDecimal(request.getParameter("proxyPriceLv3")));
        goodsCommonProxy.setCreater("1");
        goodsCommonProxy.setCreattime(DateUtil.toTimeString(new Date()));

        int i = goodsCommonProxyMapper.insert(goodsCommonProxy);
        ModelAndView modelAndView = new ModelAndView("msg");
        if (i > 0) {
            modelAndView.addObject("msg", "商品设置代理价格成功");
        } else {
            modelAndView.addObject("msg", "商品设置代理价格失败");
        }
        return modelAndView;
    }

    /**
     * 分类列表
     *
     * @return
     */
    @RequestMapping("gclass")
    public ModelAndView goods_class(@RequestParam(required = false, defaultValue = "1") int start,
                                    @RequestParam(required = false, defaultValue = "") String gcName) {
        ModelAndView modelAndView = new ModelAndView("goods/class/class_list");

        GoodsClass gc = new GoodsClass();
        gc.setStart(start);
        if (!"".equals(gcName)) {
            gc.setGcName(gcName);
        }
        // 不分页
        gc.setPageSwitch(false);

        List<GoodsClass>  goodsClassList = goodsClassMapper.findGoodsClass(gc);
        gc.setResultList(goodsClassList);
        modelAndView.addObject("page", gc);

        // treelist
        TreeListUtil treeListUtil = new TreeListUtil();
        treeListUtil.setGoodsClassNodes(goodsClassList);
        List<GoodsClass>  goodsClassListTemp = treeListUtil.buildGoodsClassTree();
        modelAndView.addObject("listTree", goodsClassListTemp);

        return modelAndView;
    }

    @RequestMapping(value = "findChildrensByPid")
    public @ResponseBody
    List<GoodsClass> findChildrensByPid(Integer pid){
        List<GoodsClass> goodsClassList = goodsClassRedisService.getGoodsClassList(pid);
        return goodsClassList;
    }

    /**
     * to-------增加商品种类
     *
     * @return
     */
    @RequestMapping(value = "gclass/toAdd")
    public ModelAndView gclassAdd(@RequestParam(required = false, defaultValue = "0") String gcParentId) {
        ModelAndView modelAndView = new ModelAndView("goods/class/class_add");

        List<GoodsClass> goodsClassListAll = new ArrayList<GoodsClass>();

        if ("0".equals(gcParentId)) {
//            List<GoodsClass> level1Gc = goodsClassRedisService.getGoodsClassList(null);
            List<GoodsClass> level1Gc = goodsClassMapper.findGoodsClass(new GoodsClass(0, false));
            for (GoodsClass goodsClass1 : level1Gc) {
                goodsClassListAll.add(goodsClass1);
//                List<GoodsClass> level2Gc =goodsClassRedisService.getGoodsClassList(goodsClass1.getGcId());
                List<GoodsClass> level2Gc = goodsClassMapper.findGoodsClass(new GoodsClass(goodsClass1.getGcId()));
                goodsClassListAll.addAll(level2Gc);
                for (GoodsClass goodsClass2 : level2Gc) {
                    goodsClass2.setGcName("&nbsp;&nbsp;&nbsp;&nbsp;" + goodsClass2.getGcName());
                }
            }

        } else {
            List<GoodsClass> level2Gc = goodsClassRedisService.getGoodsClassList(Integer.parseInt(gcParentId));
            goodsClassListAll.addAll(level2Gc);
        }

        modelAndView.addObject("goodsClassList", goodsClassListAll);
        return modelAndView;
    }

    /**
     * 属性列表
     *
     * @param attribute
     * @return
     * @throws Exception
     */
    @RequestMapping("attribute")
    @AuthPassport
    public ModelAndView attributeList(Attribute attribute) throws Exception {
        GoodsClass gc = new GoodsClass();
        gc.setGcParentId(0);
        gc.setPageSwitch(false);
        attribute.setResultList(attributeMapper.selectByCondition(attribute));
        ModelAndView view = new ModelAndView("goods/class/attributeList");
        view.addObject("goodsClassList", goodsClassMapper.findGoodsClass(gc));
        view.addObject("page", attribute);
        return view;
    }

    @RequestMapping("attribute/attributeadd")
    public ModelAndView attributeadd() throws Exception {
        GoodsClass gc = new GoodsClass();
        gc.setGcParentId(0);
        gc.setPageSwitch(false);
        ModelAndView view = new ModelAndView("goods/class/attributeadd");
        view.addObject("goodsClassList", goodsClassMapper.findGoodsClass(gc));
        return view;
    }
    @ArchivesLog(operationDescription = "新增商品属性")
    @RequestMapping("attribute/attributeadddo")
    public ModelAndView attributeadddo(Attribute attribute) {
        attributeMapper.insert(attribute);
        ModelAndView view = new ModelAndView("redirect:/goods/attribute");
        return view;
    }

    @RequestMapping("attribute/attributeedit")
    public ModelAndView attributeedit(Integer attrId) throws Exception {
        GoodsClass gc = new GoodsClass();
        gc.setGcParentId(0);
        gc.setPageSwitch(false);
        ModelAndView view = new ModelAndView("goods/class/attributeedit", "info", attributeMapper.selectByPrimaryKey(attrId));
        view.addObject("goodsClassList", goodsClassMapper.findGoodsClass(gc));
        return view;
    }
    @ArchivesLog(operationDescription = "编辑商品属性")
    @RequestMapping("attribute/attributeeditdo")
    public ModelAndView attributeeditdo(Attribute attribute) {
        attributeMapper.updateByPrimaryKeySelective(attribute);
        ModelAndView view = new ModelAndView("redirect:/goods/attribute?gcId=" + attribute.getTypeId());
        return view;
    }

    @RequestMapping("attribute/attributeerm")
    public ModelAndView attributeerm(Attribute attribute) {
        attributeMapper.deleteByPrimaryKey(attribute.getAttrId());
        ModelAndView view = new ModelAndView("redirect:/goods/attribute");
        return view;
    }

    /**
     * 品牌名称检查是否重复
     *
     * @return
     */
    @RequestMapping("gclass/checkGClassName")
    public
    @ResponseBody
    boolean checkGClassName(String gcName) {
        GoodsClass gClass = new GoodsClass();
        gClass.setGcName(gcName);
        List<GoodsClass> goodClassList = this.goodsClassMapper.findGoodsClass(gClass);
        if (goodClassList.size() > 0) {
            for(GoodsClass goodsClass : goodClassList) {
                if (gcName.equals(goodsClass.getGcName())) {
                    return false;
                }
            }
        }
        return true;
    }

    @ArchivesLog(operationDescription = "新增商品分类")
    @RequestMapping("gclass/doAdd")
    public ModelAndView addGoodClass(MultipartHttpServletRequest multipartHttpServletRequest) {

        ModelAndView modelAndView = new ModelAndView("msg");
        GoodsClass goodsClass = new GoodsClass();
        goodsClass.setGcName(multipartHttpServletRequest.getParameter("gcName"));

        goodsClass.setCommisRate(multipartHttpServletRequest.getParameter("commisRate") == null || multipartHttpServletRequest.getParameter("commisRate").equals("") ? 0 : Float.parseFloat(multipartHttpServletRequest.getParameter("commisRate")));
        goodsClass.setCommisRateSecond(multipartHttpServletRequest.getParameter("commisRateSecond") == null || multipartHttpServletRequest.getParameter("commisRateSecond").equals("") ? 0 : Float.parseFloat(multipartHttpServletRequest.getParameter("commisRateSecond")));
        goodsClass.setGcParentId(Integer.parseInt(multipartHttpServletRequest.getParameter("gcParentId")));
        goodsClass.setGcSort(Integer.parseInt(multipartHttpServletRequest.getParameter("gcSort")));
        MultipartFile pic = multipartHttpServletRequest.getFile("pic");
        if (pic.getSize() > 0) {
            String picture = super.uploadPicsWithoutCompressSize(pic, multipartHttpServletRequest, null, null);
            goodsClass.setGcImg(picture);
        }

        MultipartFile pic2 = multipartHttpServletRequest.getFile("pic2");
        if (pic2.getSize() > 0) {
            String picture2 = super.uploadPicsWithoutCompressSize(pic2, multipartHttpServletRequest, null, null);
            goodsClass.setAdvImg(picture2);
        }
        goodsClass.setGcId(0);
        goodsClass.setTypeId(1);
        goodsClass.setTypeName("");
        goodsClass.setGcTitle("");
        goodsClass.setGcKeywords("");
        goodsClass.setGcDescription("");
        int i = goodsClassMapper.insert(goodsClass);
        if (i > 0) {
            modelAndView.addObject("msg", "商品分类新增成功");
        } else {
            modelAndView.addObject("msg", "商品分类新增失败");
        }

        modelAndView.addObject("returnUrl", "goods/gclass");

        return modelAndView;
    }

    @RequestMapping("gclass/toModify")
    public ModelAndView toModifyGoodClass(Integer gcId) {
        ModelAndView modelAndView = new ModelAndView("goods/class/class_modify");
        GoodsClass goodsClass = this.goodsClassMapper.selectByPrimaryKey(gcId);

//        List<GoodsClass> goodsClassList = goodsClassMapper.findGoodsClass(new GoodsClass());
        List<GoodsClass> goodsClassListAll = new ArrayList<GoodsClass>();
//        if ("0".equals(gcParentId)) {
//            List<GoodsClass> level1Gc = goodsClassRedisService.getGoodsClassList(null);
        List<GoodsClass> level1Gc = goodsClassMapper.findGoodsClass(new GoodsClass(0, false));
        for (GoodsClass goodsClass1 : level1Gc) {
            goodsClassListAll.add(goodsClass1);
//                List<GoodsClass> level2Gc =goodsClassRedisService.getGoodsClassList(goodsClass1.getGcId());
            List<GoodsClass> level2Gc = goodsClassMapper.findGoodsClass(new GoodsClass(goodsClass1.getGcId()));
            goodsClassListAll.addAll(level2Gc);
            for (GoodsClass goodsClass2 : level2Gc) {
                goodsClass2.setGcName("&nbsp;&nbsp;&nbsp;&nbsp;" + goodsClass2.getGcName());
            }
        }

//        } else {
//            List<GoodsClass> level2Gc = goodsClassRedisService.getGoodsClassList(Integer.parseInt(gcParentId));
//            goodsClassListAll.addAll(level2Gc);
//        }
        modelAndView.addObject("goodsClassList", goodsClassListAll);
        modelAndView.addObject("goodsClass", goodsClass);
        return modelAndView;
    }

    @ArchivesLog(operationDescription = "修改商品分类")
    @RequestMapping("gclass/doModify")
    public ModelAndView doModifyGoodClass(MultipartHttpServletRequest multipartHttpServletRequest) {
        ModelAndView modelAndView = new ModelAndView("msg");

        GoodsClass goodsClass = new GoodsClass();
        goodsClass.setGcId(Integer.parseInt(multipartHttpServletRequest.getParameter("gcId")));
        goodsClass.setGcParentId(Integer.parseInt(multipartHttpServletRequest.getParameter("gcParentId")));
//        goodsClass.setGcName(multipartHttpServletRequest.getParameter("gcName"));
        goodsClass.setCommisRate(multipartHttpServletRequest.getParameter("commisRate") == null || multipartHttpServletRequest.getParameter("commisRate").equals("") ? 0 : Float.parseFloat(multipartHttpServletRequest.getParameter("commisRate")));
        goodsClass.setCommisRateSecond(multipartHttpServletRequest.getParameter("commisRateSecond") == null ||multipartHttpServletRequest.getParameter("commisRateSecond").equals("") ? 0 : Float.parseFloat(multipartHttpServletRequest.getParameter("commisRateSecond")));
        goodsClass.setGcSort(Integer.parseInt(multipartHttpServletRequest.getParameter("gcSort")));
        MultipartFile pic = multipartHttpServletRequest.getFile("pic");
        if (pic.getSize() > 0) {
            String picture = super.uploadPicsWithoutCompressSize(pic, multipartHttpServletRequest, null, null);
            goodsClass.setGcImg(picture);
        }

        MultipartFile pic2 = multipartHttpServletRequest.getFile("pic2");
        if (pic2.getSize() > 0) {
            String picture2 = super.uploadPicsWithoutCompressSize(pic2, multipartHttpServletRequest, null, null);
            goodsClass.setAdvImg(picture2);
        }
        goodsClass.setTypeId(1);//暂时先用固定1 登录功能完成后从session中取
        goodsClass.setTypeName("");
        goodsClass.setGcTitle("");
        goodsClass.setGcKeywords("");
        goodsClass.setGcDescription("");
        int i = goodsClassMapper.updateByPrimaryKeySelective(goodsClass);
        if (i > 0) {
            modelAndView.addObject("msg", "商品分类修改成功");
        } else {
            modelAndView.addObject("msg", "商品分类修改失败");
        }

        modelAndView.addObject("returnUrl", "goods/gclass");

        return modelAndView;
    }

    /**
     * 删除类别
     */
    @ArchivesLog(operationDescription = "删除商品分类")
    @RequestMapping("gclass/delGclass")
    public ModelAndView delGclass(HttpServletRequest request) {
        // request.getParameterValues("acId") = 13,14,16,17
        String[] gcIds = request.getParameterValues("gcId")[0].split(",");
        ModelAndView modelAndView = new ModelAndView("msg");
        int i = 0;
        for (String id : gcIds) {
            i += goodsClassMapper.deleteByPrimaryKey(Integer.parseInt(id));
        }

        if (i == gcIds.length) {
            modelAndView.addObject("msg", "商品分类删除成功");
        } else {
            modelAndView.addObject("msg", "商品分类删除失败");
        }

        modelAndView.addObject("returnUrl", "goods/gclass");
        return modelAndView;
    }

    /**
     * 规格列表
     *
     * @return
     */
    @RequestMapping("specification")
    public ModelAndView specification(@RequestParam(required = false, defaultValue = "1") int start,
                                      @RequestParam(required = false) String spName,
                                      @RequestParam(required = false) String classId) {

        ModelAndView res = new ModelAndView("goods/spec/specification");
        Spec spec = new Spec();
        spec.setStart(start);
        spec.setSpParentId(0);
        spec.setSpName(StringUtils.isBlank(spName) ? null : spName);
        spec.setIsQueryRelation(true);
        spec.setClassId(StringUtils.isBlank(classId) ? null : Integer.parseInt(classId));
        List<Spec>  specList= specMapper.findSpecWithSonByCondition(spec);
        spec.setResultList(specList);
        res.addObject("page", spec);
        return res;
    }

    /**
     * 新增规格与商品分类表关联
     * @return
     */
    @RequestMapping(value = "specification/toAddSpec")
    public String toAddSpec(){
        return "goods/spec/spec_add";
    }

    /**
     * 规格插入
     * @param spec
     * @return
     */
    @RequestMapping(value = "specification/doAddSpec")
    @ArchivesLog(operationDescription = "新增规格")
    public @ResponseBody boolean doAddSpec(Spec spec){

        spec.setSpParentId(0);
        List<Spec> specList = specMapper.findSpec(new Spec(spec.getClassId()));
        if(specList.size()<1){
            int i = specMapper.insertSelective(spec);
            if(i==1)
                return true;
            else
                return false;
        }else{
            return false;
        }
    }

    @RequestMapping(value = "specification/toManagerSpec")
    public ModelAndView toManagerSpec(Integer spId){
        ModelAndView res = new ModelAndView("goods/spec/spec_manager");
        Spec  spec= specMapper.getSpecWithChildrenById(spId);
        res.addObject("pageBean",spec);
        return res;
    }

    /**
     * 规格插入
     * @param spec
     * @return
     */
    @ArchivesLog(operationDescription = "新增规格属性")
    @RequestMapping(value = "specification/doAddSpecBatch")
    public @ResponseBody boolean doAddSpecBatch(Spec spec){
        for(Spec record:spec.getSpecList()){
            if(StringUtils.isBlank(record.getSpName()))
                continue;
            specMapper.insertSelective(record);
        }

        return true;
    }

    @ArchivesLog(operationDescription = "删除规格")
    @RequestMapping(value = "specification/delSpec")
    public @ResponseBody
    AjaxReturnData  delSpec(Integer[] spIds){
        AjaxReturnData ajaxReturnData = new AjaxReturnData();
        for(Integer spId:spIds){
            Spec spec = new Spec();
            spec.setSpParentId(spId);
            List<Spec> specList = specMapper.findSpec(spec);
            for(Spec record:specList){
                //删除对应的属性值
                specValueMapper.deleteBySpId(record.getSpId());
            }

            //删除子记录
            specMapper.deleteByParentId(spId);

            //删除本记录
            specMapper.deleteByPrimaryKey(spId);

        }
        ajaxReturnData.setMessage("删除成功");
        ajaxReturnData.setType("succ");
        ajaxReturnData.setUrl("spec/specList");
        return ajaxReturnData;
    }

    @RequestMapping(value = "specification/findSpecValueBySpId")
    public ModelAndView findSpecValueBySpId(@RequestParam(required = true)Integer spId,
                                            @RequestParam(required = false,defaultValue = "1") int p,
                                            @RequestParam(required = true)Integer spParentId){
        ModelAndView res = new ModelAndView("goods/spec/spec_value_manager");

        SpecValue specValue = new SpecValue();
        specValue.setSpId(spId);
        specValue.setStart(p);
        specValue.setPageSize(10);
        Spec spec = specMapper.selectByPrimaryKey(spId);
        List<SpecValue> specValueList = specValueMapper.findSpecValue(specValue);

        for (SpecValue specValue1: specValueList) {
            if (specValue1.getStoreId() != 0) {
                Store store = storeMapper.selectStoreByPrimaryKey(specValue1.getStoreId());
                specValue1.setStoreName(store.getStoreName());
            }
        }

        specValue.setResultList(specValueList);
        res.addObject("specValueInfo", specValue);
        res.addObject("spec", spec);
        res.addObject("spParentId", spParentId);
        return res;
    }

    @ArchivesLog(operationDescription = "删除规格属性值")
    @RequestMapping(value = "specification/delSpecValue")
    public @ResponseBody boolean delSpecValue(Integer spValueIds){
        specValueMapper.deleteByPrimaryKey(spValueIds);
        return true;
    }

    @ArchivesLog(operationDescription = "新增规格属性值")
    @RequestMapping(value = "specification/doAddSpValues")
    public @ResponseBody boolean doAddSpValues(Spec spec){
        if(spec!=null){
            for(SpecValue specValue:spec.getSpecValueList()){
                if(StringUtils.isBlank(specValue.getSpValueName()))
                    continue;
                specValueMapper.insertSelective(specValue);
            }
        }
        return true;
    }

    /**
     * 商品批量下架
     *
     * @return
     * @throws Exception
     */
    @ArchivesLog(operationDescription = "下架商品")
    @RequestMapping(value = "goodsList/dropGoodsBatch")
    public ModelAndView dropGoodsBatch(String goodsCommonIds[]) throws Exception {
        AjaxReturnData data = new AjaxReturnData();
        data.setUrl("goods/goodsList");
        data.setMessage("商品下架成功");
        AjaxMsgTypeEnum.SUCC.setText(data.getType());
        goodsService.modifyGoodsStatusByBatch(goodsCommonIds, "10");

        /********下架专区**********/
        Map map = new HashMap();
        map.put("state","-1");
        map.put("goodsCommonids",goodsCommonIds);
        activeAreaGoodsMapper.updateStateByGoodsCommonids(map);

        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", "商品下架成功");
        modelAndView.addObject("returnUrl", "goods/goodsList");
        return modelAndView;
    }

    /**
     * 商品批量下架恢复
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "goodsList/restoreGoodsBatch")
    @ArchivesLog(operationDescription = "恢复商品上架")
    public ModelAndView restoreGoodsBatch(String goodsCommonIds[]) throws Exception {
        AjaxReturnData data = new AjaxReturnData();
        data.setUrl("goods/goodsList");
        AjaxMsgTypeEnum.SUCC.setText(data.getType());
        goodsService.modifyGoodsStatusByBatch(goodsCommonIds, "1");

        /********专区**********/
        Map map = new HashMap();
        map.put("state","1");
        map.put("goodsCommonids",goodsCommonIds);
        activeAreaGoodsMapper.updateStateByGoodsCommonids(map);

        ModelAndView modelAndView = new ModelAndView("msg");
        modelAndView.addObject("msg", "商品恢复下架成功！");
        modelAndView.addObject("returnUrl", "goods/goodsList?goodsState=10");
        return modelAndView;
    }

    /**
     * 审核商品
     *
     * @param goodsCommon
     * @return
     */
    @ArchivesLog(operationDescription = "审核商品上架")
    @RequestMapping(value = "goodsVerify")
    public ModelAndView goodsVerify(GoodsCommon goodsCommon) {
        ModelAndView modelAndView = new ModelAndView("redirect:/goods/goodsList");
        Integer ids[] = new Integer[1];
        ids[0] = goodsCommon.getGoodsCommonid();
        goodsService.goodsVerifyByBatch(ids, 1, 1);

        /********专区**********/
        Map map = new HashMap();
        map.put("state","1");
        map.put("goodsCommonids", new String[]{goodsCommon.getGoodsCommonid() + ""});
        activeAreaGoodsMapper.updateStateByGoodsCommonids(map);

        return modelAndView;
    }

    /**
     * 审核商品
     *
     * @param goodsCommon
     * @return
     */

    @ArchivesLog(operationDescription = "审核拒绝通过")
    @RequestMapping(value = "refuseGoodsVerify")
    public ModelAndView refuseGoodsVerify(GoodsCommon goodsCommon) {
        ModelAndView modelAndView = new ModelAndView("redirect:/goods/goodsList");
        Integer ids[] = new Integer[1];
        ids[0] = goodsCommon.getGoodsCommonid();
        goodsService.goodsVerifyByBatch(ids, 0,0);

        /********专区**********/
        Map map = new HashMap();
        map.put("state","-1");
        map.put("goodsCommonids",new String[]{goodsCommon.getGoodsCommonid()+""});
        activeAreaGoodsMapper.updateStateByGoodsCommonids(map);

        return modelAndView;
    }

    /**
     * 审核商品
     *
     * @param
     * @return
     */

    @ArchivesLog(operationDescription = "审核商品上架")
    @RequestMapping(value = "goodsVerifyByBatch")
    public ModelAndView goodsVerifyByBatch(Integer goodsCommonIds[]) {
        ModelAndView modelAndView = new ModelAndView("redirect:/goods/goodsList");
        goodsService.goodsVerifyByBatch(goodsCommonIds, 1,1);

        /********专区**********/
        Map map = new HashMap();
        map.put("state","1");
        map.put("goodsCommonids",goodsCommonIds);
        activeAreaGoodsMapper.updateStateByGoodsCommonids(map);

        return modelAndView;
    }

    /**
     * 相册列表页
     *
     * @return
     */
    @RequestMapping(value = "album")
    public ModelAndView albumList(AlbumClass albumClass) {
        ModelAndView modelAndView = new ModelAndView("goods/album/albumList");
        // 查询所有店铺信息
        Store store = new Store();
        store.setPageSwitch(false);
        List<Store> storeList = storeMapper.findStoreByCondition(store);
        modelAndView.addObject("storeList", storeList);
        // 查询相册
        List<AlbumClass> album = albumClassMapper.selectByCondition(albumClass);
        albumClass.setResultList(album);
        modelAndView.addObject("page", albumClass);
        return modelAndView;
    }

    /**
     * 删除，只删除相册数据，不删除图片数据，相册图片更新到其他相册
     *
     * @param albumId
     * @return
     */
    @ArchivesLog(operationDescription = "删除相册")
    @RequestMapping(value = "albumDelete")
    public ModelAndView albumDel(Integer albumId) {
        AjaxReturnData data = new AjaxReturnData();
        data.setMessage("相册删除成功");
        data.setType(AjaxMsgTypeEnum.SUCC.getText());
        if (albumId != null) {
            albumClassMapper.updateDelAlbumPic(albumId);
            albumClassMapper.deleteByPrimaryKey(albumId);
        } else {
            data.setMessage("相册删除异常");
            data.setType(AjaxMsgTypeEnum.INFO.getText());
        }
        return new ModelAndView("redirect:/goods/album");
    }

    /**
     * 图片分页列表
     *
     * @return
     */
    @RequestMapping(value = "album/picList")
    public ModelAndView picList(AlbumPicPageBean pageBean) {
        ModelAndView modelAndView = new ModelAndView("goods/album/picList");
        // 查询所有店铺信息
        Store store = new Store();
        store.setPageSwitch(false);
        List<Store> storeList = storeMapper.findStoreByCondition(store);
        modelAndView.addObject("storeList", storeList);

        List<AlbumPic> albumPics = picDao.getAlbumPicList(pageBean);
        pageBean.setPageSize(20);
        pageBean.setResultList(albumPics);
        modelAndView.addObject("page", pageBean);
        return modelAndView;
    }

    /**
     * 图片删除：数据库数据删除，云端图片删除
     *
     * @param picId
     * @return
     */
    @ArchivesLog(operationDescription = "删除图片")
    @RequestMapping(value = "album/picDel", method = RequestMethod.POST)
    public ModelAndView pic_del(@RequestParam Integer albumId, @RequestParam String picId) {
        LOGGER.debug("pics:" + picId + ",");
        AjaxReturnData res = new AjaxReturnData();
        String[] ids = picId.split(",");
        for (String i : ids) {
            int s = picDao.deleteByPrimaryKey(Integer.parseInt(i));
            if (s > 0) {
                // TODO 删除云端图片
                res.setMessage("图片删除成功");
                res.setType(AjaxMsgTypeEnum.SUCC.getText());
            } else {
                res.setType(AjaxMsgTypeEnum.INFO.getText());
                res.setMessage("图片删除失败");
            }
        }
        return new ModelAndView("redirect:/goods/album/picList?aclassId=" + albumId);
    }

    /**商品标签管理*/

    @RequestMapping(value = "tagList")
    public ModelAndView tagList(@RequestParam(required = false,defaultValue = "1")Integer p,String tagName){
        ModelAndView res = new ModelAndView("goods/tag/tag_list");
        GoodsTag goodsTag = new GoodsTag();
        goodsTag.setStart(p);
        goodsTag.setTagName(StringUtils.isBlank(tagName) ? null : tagName);
        goodsTag.setPageSwitch(false);
        List<GoodsTag> goodsTagList = goodsTagService.selectListByCondition(goodsTag);
        goodsTag.setResultList(goodsTagList);
        res.addObject("pageBean", goodsTag);
        return res;
    }

    /**
     * 跳转到添加标签页面
     * @return
     */
    @RequestMapping(value = "tagList/toAddTag")
    public ModelAndView toAddTag(){
        ModelAndView res = new ModelAndView("goods/tag/tag_add");

        List<Festival> festivalList = festivalMapper.selectListByCondition(new Festival(false));
        res.addObject("festivalList", festivalList);
        List<Relation> relationList = relationMapper.selectListByCondition(new Relation(false));
        res.addObject("relationList", relationList);
        return res;
    }

    /**
     * 商品标签
     * @param goodsTag
     * @param fIds
     * @param rIds
     * @param session
     * @return
     */
    @AuthPassport
    @RequestMapping(value = "tagList/doAddTag")
    @ArchivesLog(operationDescription = "新增标签")
    public @ResponseBody boolean doAddTag(GoodsTag goodsTag,
                                          Integer[] fIds,
                                          Integer[] rIds,HttpSession session){
        MemberBase adminInfo = (MemberBase)session.getAttribute("memInfo");
        goodsTag.setCreateName(adminInfo.getTrueName());
        goodsTag.setCreateTime(DateUtil.getCurrentDateTime());
        goodsTag.setCreaterId(adminInfo.getUserId());
        boolean result = goodsTagService.addGoodsTag(goodsTag,fIds,rIds);
        return result;
    }

    @AuthPassport
    @RequestMapping(value = "tagList/toEditTag")
    public ModelAndView toEditTag(Integer tagId){
        ModelAndView res = new ModelAndView("goods/tag/tag_edit");
        List<Festival> festivalList = festivalMapper.selectListByCondition(new Festival(false));
        res.addObject("festivalList", festivalList);
        List<Relation> relationList = relationMapper.selectListByCondition(new Relation(false));
        res.addObject("relationList", relationList);
        GoodsTag goodsTag = new GoodsTag();
        goodsTag.setTagId(tagId);
        List<GoodsTag> goodsTagList = goodsTagService.selectListByCondition(goodsTag);
        if(goodsTagList.size()>0){
            res.addObject("goodsTag", goodsTagList.get(0));
        }
        return res;
    }

    @AuthPassport
    @RequestMapping(value = "tagList/doEditTag")
    @ArchivesLog(operationDescription = "编辑标签")
    public @ResponseBody boolean doEditTag(GoodsTag goodsTag, Integer[] fIds, Integer[] rIds){
        boolean result = goodsTagService.updateGoodsTag(goodsTag, fIds, rIds);
        if(!result){
            return false;
        }

        return true;
    }

    @AuthPassport
    @RequestMapping(value = "tagList/delTag")
    @ArchivesLog(operationDescription = "删除标签")
    public @ResponseBody AjaxReturnData delTag(Integer[] tagIds){
        AjaxReturnData ajaxReturnData = new AjaxReturnData();
        boolean result = goodsTagService.batchDeleteGoodsTags(tagIds);
        if(result){
            ajaxReturnData.setMessage("删除成功");
            ajaxReturnData.setType(AjaxMsgTypeEnum.SUCC.getText());
            ajaxReturnData.setUrl("tag/tagList");
        }else{
            ajaxReturnData.setMessage("操作出现异常，请联系相关工作人员");
            ajaxReturnData.setType("failed");
//            ajaxReturnData.setUrl("tag/tagList");
        }

        return ajaxReturnData;
    }

    /**
     * 根据goodsCommonid查询该商品详情
     * @param goodsCommonid
     * @return
     */
    @RequestMapping(value = "goodsInfo")
    public @ResponseBody List<Goods> getGoodsInfo(Integer goodsCommonid){
        Assert.notNull(goodsCommonid, "GoodsCommonid could not be none");

        Goods goods = new Goods();
        goods.setGoodsCommonid(goodsCommonid);
        List<Goods> goodsList =  goodsService.selectByCondition(goods);

        return goodsList;
    }
}
